package org.springframework.samples.petclinic.web;

import java.io.IOException;
import java.util.Map;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Alien;
import org.springframework.samples.petclinic.model.Email;
import org.springframework.samples.petclinic.service.ClinicService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes(types = Email.class)
public class EmailController {

    private final ClinicService clinicService;
    private static Logger logger = LoggerFactory.getLogger(EmailController.class);

    @Autowired
    public EmailController(ClinicService clinicService) {
        this.clinicService = clinicService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
    }

    @RequestMapping(value = "/emails/new", method = RequestMethod.GET)
    public String initCreationForm(Map<String, Object> model) {
    	Email email = new Email();
        model.put("email", email);
        return "emails/sendEmailForm";
    }

    @RequestMapping(value = "/emails/new", method = RequestMethod.POST)
    public String processCreationForm(@Valid Email email, BindingResult result, SessionStatus status, HttpServletResponse response) throws InterruptedException, IOException {
        if (!email.getExpectedPassword().equals(email.getPassword())) {
        	response.sendError(401, "Nieprawidłowe hasło");
        	return null;
        }
    	if (result.hasErrors()) {
            return "/emails/new";
        } else {
    		try {
    			 
    			Context initCtx = new InitialContext();
    			Context envCtx = (Context) initCtx.lookup("java:comp/env");
    			Session session = (Session) envCtx.lookup("mail/Session");

    			Message message = new MimeMessage(session);
    			message.setFrom(new InternetAddress(email.getFrom()));
    			InternetAddress to[] = new InternetAddress[1];
    			to[0] = new InternetAddress(email.getRecipients());
    			message.setRecipients(Message.RecipientType.TO, to);
    			message.setSubject(email.getSubject());
    			message.setContent(email.getText(), "text/plain");
    			Transport.send(message);
    			email.setSent(true);
    		} catch (MessagingException e) {
    			email.setSent(false);
    			logger.error("email error: ", e);
    			throw new RuntimeException(e);
    		} catch (NamingException e) {
    			email.setSent(false);
    			logger.error("email error: ", e);
    			throw new RuntimeException(e);
			}
    		
            status.setComplete();
            return "redirect:/emails/new" ;
        }
    }
    
}
